package com.deli.core.service;

import com.deli.core.dao.BrandDAO;
import com.deli.core.dao.ColorDAO;
import com.deli.core.dao.ProductDAO;
import com.deli.core.dao.SkuDAO;
import com.deli.core.pojo.Brand;
import com.deli.core.pojo.Color;
import com.deli.core.pojo.Product;
import com.deli.core.pojo.Sku;
import com.deli.core.tools.PageHelper;
import com.deli.core.tools.PageHelper.Page;
import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.IOException;
import java.util.*;

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDAO productDAO;
    @Autowired
    private BrandDAO brandDAO;
    @Autowired
    private ColorDAO colorDAO;
    @Autowired
    private SkuDAO skuDAO;
    @Autowired
    private Jedis jedis;
    @Autowired
    private HttpSolrServer solrServer;
    @Autowired
    private JmsTemplate jmsTemplate;


    @Override
    public Page<Product> productShowAll(Product product, Integer pageNum,
                                        Integer pageSize) {
        if (product.getName() == null) {
            product.setName("");
        }
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Product.class);
        Criteria andLike = example.createCriteria().andLike("name",
                "%" + product.getName() + "%");
        Integer aa = product.getIsShow() == null ? 1 : product.getIsShow();
        if (product.getBrandId() == null) {
            andLike.andEqualTo("isShow", aa);
            example.setOrderByClause("id desc");
        } else {
            andLike.andEqualTo("isShow", aa).andEqualTo("brandId", product.getBrandId());
            example.setOrderByClause("id desc");
        }
        productDAO.selectByExample(example);
        Page<Product> page = PageHelper.endPage();
        return page;

    }

    @Override
    public List<Brand> findBrandAll() {
        return brandDAO.select(null);
    }

    @Override
    public List<Product> productShowAdd(Product product) {

        return productDAO.select(product);
    }

    @Override
    public List<Color> findColordAll() {
        Example example = new Example(Color.class);
        example.createCriteria().andNotEqualTo("parentId", "0");
        return colorDAO.selectByExample(example);
    }

    @Override
    public void productDoAdd(Product product) {

        // 设置默认值
        if (product.getIsShow() == null) {
            product.setIsShow(0);
        }
        // 设置默认值
        if (product.getIsCommend() == null) {
            product.setIsCommend(0);
        }
        // 设置默认值
        if (product.getIsHot() == null) {
            product.setIsHot(0);
        }
        // 设置默认值
        if (product.getIsNew() == null) {
            product.setIsNew(0);
        }
        if (product.getCreateTime() == null) {
            product.setCreateTime(new Date());
        }
        // 先添加商品到数据库中
        Long incr = jedis.incr("pno");
        product.setId(incr);
        productDAO.insert(product);

        System.out.println("获得回显id" + product.getId());

        // 将商品信息添加到库存表中
        // 遍历不同的颜色和尺码
        // 每一个不同颜色，或者不同尺码，都应该插入库存表中，成为一条数据
        String[] colors = product.getColors().split(",");
        String[] sizes = product.getSizes().split(",");

        for (String color : colors) {
            for (String size : sizes) {
                Sku sku = new Sku();
                sku.setProductId(product.getId());
                sku.setColorId(Long.parseLong(color));
                sku.setSize(size);
                sku.setMarketPrice(1000.00f);
                sku.setPrice(800.00f);
                sku.setDeliveFee(20f);
                sku.setStock(0);
                sku.setUpperLimit(100);
                sku.setCreateTime(new Date());

                skuDAO.insert(sku);
            }
        }

    }

    @Override
    public void updatebyisShow(Product product,final String ids) {
        String[] idss = ids.split(",");
        //方式一:将遍历之后的id存放在list集合中一次性全部修改完毕
        List<Object> list = new ArrayList<Object>();
        for (String id : idss) {
            //product.setId(Long.parseLong(id));
            //修改的方式二:但是这种方法效率比较慢,在循环内,数据库要反复的开合关
            //productDAO.updateByPrimaryKeySelective(product);
            list.add(Long.parseLong(id));
        }
        Example example = new Example(Product.class);
        example.createCriteria().andIn("id", list);
        productDAO.updateByExampleSelective(product, example);
        /**
         * 将上架的商品的id存入到mq中
         *
         */
        if(product.getIsShow()!=null&&product.getIsShow()==1){
            jmsTemplate.send("productIds", new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    //创建文本文件
                    return  session.createTextMessage(ids);
                }
            });
        }


    }

    public Map<String, Object> findProductById(Long id) {
        Product product = productDAO.selectByPrimaryKey(id);

        List<Map<String,Object>> skus = skuDAO.findSKuAndColorByProductId(id);
        Map<String, Object> map = new LinkedHashMap<String,Object>();
        map.put("product", product);
        map.put("skus", skus);
        return map;
    }
}
